<template>
  <div class="app-container">
    <div>
      <el-row class="admin-top-g">
        <GButton
          :is-add-show="false"
          :is-edit-show="false"
          :is-del-show="!!(limits.length >=1 && limits.filter(it => it.FName === '删除').length)"
          :lists="options"
          :is-settings-show = "lookSetShow"
          :is-plus-show="false"
          @onAdd="addUser"
          @onEdit="editUser"
          @onDelete="delUser"
          @onPlus="onPlus"
          @selectSettings="selectSettings"
      /></el-row>
      <br>

      <el-row class="common-row">
        <template v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length">
          <el-input v-model="keyword" clearable style="width: 200px;" placeholder="请输入关键字" @keyup.native.enter="searchUser" @change="searchUser"/>
          <el-select v-model="brand" clearable style="width: 120px;" placeholder="请选择品牌" @change="selectBrand">
            <el-option
              v-for="item in fbrandList"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>

          <el-select v-model="fisqrjx" clearable filterable style="width: 150px;" placeholder="请选择" @change="searchUser">
            <el-option
              v-for="item in fqrlist"
              :key="item.finterid"
              :label="item.fname"
              :value="item.finterid"/>
          </el-select>

          <el-button type="primary" icon="el-icon-search" @click="searchUser">搜索</el-button>
        </template>

        <el-button v-if="limits.length >=1 && limits.filter(it => it.FName === '导出').length" type="primary" icon="el-icon-download" @click="downData">导出</el-button>
        <el-button type="primary" @click="(confirmJx(1))">确认数据</el-button>

      </el-row>
    </div>
    <br>
    <el-table
      v-loading="listLoading"
      v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
      :data="tableData"
      :header-cell-style="tableHeaderStyle"
      :height="tableHeight"
      class="tableCss"
      element-loading-text="正在加载"
      border
      highlight-current-row
      @row-dblclick="detailDbclick"
      @cell-dblclick="editData"
      @selection-change="handleSelectionChange"
      @current-change="salaryCurrentChange">
      <el-table-column
        type="selection"
        width="55"/>
      <template v-for="item in formThead">
        <el-table-column v-if="item.frpttypeflag ==0" :key="item.fid" :prop="item.frepfld" :label="item.frepcap" :width="item.frepwid" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <template v-if="item.frephide<=0">
              <template v-if="item.frepfld === 'fstatus'">
                <el-tag v-if="Number(scope.row[item.frepfld]) === 1" size="mini" type="success">已审</el-tag>
                <el-tag v-else size="mini" type="danger">未审</el-tag>
              </template>
              <template v-else-if="item.frepfld === 'fisqrname'">
                <el-tag v-if="Number(scope.row[item.frepfld]) === 1" size="mini" type="success">已完成</el-tag>
                <el-tag v-else size="mini" type="danger">未完成</el-tag>
              </template>
              <template v-else-if="Number(item.freptype)===131" size="mini">
                {{ Number(scope.row[item.frepfld]).toFixed(2) }}
              </template>
              <template v-else size="mini">
                {{ scope.row[item.frepfld] }}
              </template>
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <el-pagination
      v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
      :total="total"
      :page-sizes="pagesizes"
      :page-size="pagesize"
      :current-page.sync="currentPage"
      class="jy-pagination"
      style="text-align: center; margin-top: 20px;"
      background
      layout="sizes, prev, pager, next, total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/>

    <el-dialog v-el-drag-dialog :visible.sync="addUserModal" title="添加／编辑" width="30%">
      <hr style="height:1px;margin-top:-33px;border:none;border-top:1px solid #ddd;" >
      <el-form v-loading="loadingForm" ref="form" :rules="rules" :inline="true" :model="form" label-width="150px" class="form1">

        <el-row >
          <el-col v-for="item in dialogThead" :span="24" :key="item.fid ">

            <el-form-item :label="item.frepcap" :prop="item.frepfld" >
              <template v-if="item.frepmeg == 1">
                <template v-for="base in baseList" v-if="base.name === item.frepfld" >
                  <el-select v-model="form[item.frepfld]" :key="base.name" class="select_el" clearable filterable placeholder="请选择">
                    <el-option
                      v-for="item2 in base[item.frepfld]"
                      :key="item2.finterid"
                      :label="item2.fname"
                      :value="item2.finterid"/>
                  </el-select>
                </template>
              </template>
              <!-- 多文本-->
              <template v-else-if="item.frepmeg == 6" >
                <template >
                  <el-input :rows="3" v-model="form[item.frepfld]" type="textarea" />
                </template>
              </template>
              <!-- 日期框-->
              <template v-else-if="item.frepmeg == 4" >
                <template >
                  <el-date-picker v-model="form[item.frepfld]" style="width:100%" class="date_el" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
                </template>
              </template>
              <!-- 禁止编辑-->
              <template v-else-if="item.frepmeg == 5" >
                <template >
                  <el-input v-model="form[item.frepfld]" :disabled="editText"/>
                </template>
              </template>

              <!-- 输入框 -->
              <template v-else >
                <el-input v-model="form[item.frepfld]" />
              </template>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="dialog-footer">
          <el-form-item >
            <el-button :loading="loadingForm" type="primary" @click="confirm" >确认</el-button>
            <el-button @click="addUserModal=false">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>

    <!-- 参数配置 -->
    <el-dialog v-el-drag-dialog :visible.sync="configModal" :close-on-click-modal="false" class="config-dialog">
      <head-table
        :config-list="configList"
        :key-value="key"
        @updateConfigData="getUpdateConfigData" />
    </el-dialog>

    <!-- SQL弹窗 -->
    <el-dialog v-el-drag-dialog :visible.sync="dialogSQLModal" :append-to-body="true" title="执行结果">
      <el-form v-loading="loadingFormSQL" ref="formSQL" :rules="rulesSQL" :model="formSQL" label-width="120px">
        <el-form-item label="SQL语句" prop="gzsql">
          <el-input v-model="formSQL.gzsql" :autosize="{ minRows: 14 }" type="textarea" style="width:400px;"/>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loadingFormSQL" type="primary" @click="confirmSQL" >确认</el-button>
          <el-button @click="dialogSQLModal=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 下载模板 -->
    <el-dialog :visible.sync="tableSetExcel" title="提示：信息导出" style="width:30%; margin:auto;">
      <el-button type="primary" @click="downloadFile1()">导出</el-button>
    </el-dialog>

    <el-dialog
      v-el-drag-dialog
      :visible.sync="detailSettings.fdetailModal"
      :close-on-click-modal="false"
      title="详情"
      class="config-dialog detail-dialog">
      <el-table
        v-loading="detailSettings.fdetailLoading"
        ref="fdetailTable"
        :header-cell-style="tableHeaderStyle"
        :data="detailSettings.fdetailData"
        style="margin-top: 10px;"
        max-height="500"
        class="tableCss"
        element-loading-text="正在加载"
        border
        highlight-current-row>
        <el-table-column
          v-for="(item, key) in detailSettings.detailFormThead"
          :key="key"
          :prop="item"
          :label="item"
          align="center">
          <template slot-scope="scope">{{ scope.row[item] }}</template>
        </el-table-column>
      </el-table>
      <!--
      <br>
      <el-pagination
        :total="detailSettings.total"
        :page-sizes="detailSettings.pagesizes"
        :page-size="detailSettings.pagesize"
        :current-page.sync="detailSettings.currentPage"
        class="jy-pagination"
        style="text-align: center; margin-top: 20px;"
        background
        layout="sizes, prev, pager, next, total"
        @size-change="detailSizeChange"
        @current-change="detailCurrentChange"/>
         -->
    </el-dialog>

    <!-- 双击明细 -->
    <el-dialog
      v-el-drag-dialog
      :visible.sync="rowDetail.fModal"
      :close-on-click-modal="false"
      title="详情"
      class="row-detail-dialog detail-dialog">
      <el-table
        v-loading="rowDetail.fLoading"
        ref="fdetailTable"
        :header-cell-style="tableHeaderStyle"
        :data="rowDetail.tableData"
        style="margin-top: 10px;"
        max-height="500"
        class="tableCss"
        element-loading-text="正在加载"
        border
        highlight-current-row>
        <el-table-column align="center" label="品牌" width="120">
          <template slot-scope="scope">{{ scope.row.fbrand }}</template>
        </el-table-column>
        <el-table-column align="center" label="主计量单位" width="120">
          <template slot-scope="scope">{{ scope.row.funit }}</template>
        </el-table-column>
        <el-table-column align="center" label="型号" width="120">
          <template slot-scope="scope">{{ scope.row.fmodel }}</template>
        </el-table-column>
        <el-table-column align="center" label="功率千瓦时" width="120">
          <template slot-scope="scope">{{ scope.row.fpower }}</template>
        </el-table-column>
        <el-table-column align="center" label="马力" width="120">
          <template slot-scope="scope">{{ scope.row.fmoli }}</template>
        </el-table-column>
        <el-table-column align="center" label="转速rpm" width="120">
          <template slot-scope="scope">{{ scope.row.fzhuansu }}</template>
        </el-table-column>
        <el-table-column align="center" label="主机重量吨" width="120">
          <template slot-scope="scope">{{ scope.row.fzjweight }}</template>
        </el-table-column>
        <el-table-column align="center" label="燃油kg" width="120">
          <template slot-scope="scope">{{ scope.row.fdieseloil }}</template>
        </el-table-column>
        <el-table-column align="center" label="燃气kg" width="120">
          <template slot-scope="scope">{{ scope.row.fgas }}</template>
        </el-table-column>
        <el-table-column align="center" label="气缸油kg" width="120">
          <template slot-scope="scope">{{ scope.row.fcylinderoil }}</template>
        </el-table-column>
        <el-table-column align="center" label="图纸送审费CCS" width="120">
          <template slot-scope="scope">{{ scope.row.ftuzhissccs }}</template>
        </el-table-column>
        <el-table-column align="center" label="图纸送审费ABS" width="120">
          <template slot-scope="scope">{{ scope.row.ftuzhissabs }}</template>
        </el-table-column>
        <el-table-column align="center" label="图纸送审费LR" width="120">
          <template slot-scope="scope">{{ scope.row.ftuzhisslr }}</template>
        </el-table-column>
        <el-table-column align="center" label="图纸送审费BV" width="120">
          <template slot-scope="scope">{{ scope.row.ftuzhissbv }}</template>
        </el-table-column>
        <el-table-column align="center" label="图纸送审费NK" width="120">
          <template slot-scope="scope">{{ scope.row.ftuzhissnk }}</template>
        </el-table-column>
        <el-table-column align="center" label="图纸送审费DNV-GL" width="120">
          <template slot-scope="scope">{{ scope.row.ftuzhissdnvgl }}</template>
        </el-table-column>
        <el-table-column align="center" label="自制件总重量" width="120">
          <template slot-scope="scope">{{ scope.row.fzzjweight }}</template>
        </el-table-column>
        <el-table-column align="center" label="焊接工时" width="120">
          <template slot-scope="scope">{{ scope.row.fhanjiegs }}</template>
        </el-table-column>
        <el-table-column align="center" label="机加工工时" width="120">
          <template slot-scope="scope">{{ scope.row.fjijiags }}</template>
        </el-table-column>
        <el-table-column align="center" label="装试工时" width="120">
          <template slot-scope="scope">{{ scope.row.fzhuangshigs }}</template>
        </el-table-column>
        <el-table-column align="center" label="合计工时" width="120">
          <template slot-scope="scope">{{ scope.row.fhejigs }}</template>
        </el-table-column>
        <el-table-column align="center" label="辅料" width="120">
          <template slot-scope="scope">{{ scope.row.ffuliao }}</template>
        </el-table-column>
        <el-table-column align="center" label="包装物" width="120">
          <template slot-scope="scope">{{ scope.row.fpackage }}</template>
        </el-table-column>
        <el-table-column align="center" label="辅料包装物基数" width="120">
          <template slot-scope="scope">{{ scope.row.ffuliaopakeage }}</template>
        </el-table-column>
        <el-table-column align="center" label="SCR安装调试工时" width="120">
          <template slot-scope="scope">{{ scope.row.fscrgs }}</template>
        </el-table-column>
        <el-table-column align="center" label="SCR平台重量吨" width="120">
          <template slot-scope="scope">{{ scope.row.fscrptweight }}</template>
        </el-table-column>
        <el-table-column align="center" label="SCR管路重量吨" width="120">
          <template slot-scope="scope">{{ scope.row.fscrglweight }}</template>
        </el-table-column>
        <el-table-column align="center" label="管路固定支架重量吨" width="120">
          <template slot-scope="scope">{{ scope.row.fglzhijiaweight }}</template>
        </el-table-column>
        <el-table-column align="center" label="HPSCR膨胀节规格" width="120">
          <template slot-scope="scope">{{ scope.row.fhpscrgg }}</template>
        </el-table-column>
        <el-table-column align="center" label="LPSCR膨胀节规格" width="120">
          <template slot-scope="scope">{{ scope.row.flpscrgg }}</template>
        </el-table-column>
        <el-table-column align="center" label="备注" width="120">
          <template slot-scope="scope">{{ scope.row.fremark }}</template>
        </el-table-column>
        <el-table-column align="center" label="日期" width="120">
          <template slot-scope="scope">{{ scope.row.fcreatetime }}</template>
        </el-table-column>
        <el-table-column align="center" label="扭振计算" width="120">
          <template slot-scope="scope">{{ scope.row.fniuzhenrmb }}</template>
        </el-table-column>
        <el-table-column align="center" label="审核" width="120">
          <template slot-scope="scope">{{ scope.row.fstatus }}</template>
        </el-table-column>
        <el-table-column align="center" label="审核人" width="120">
          <template slot-scope="scope">{{ scope.row.checkname }}</template>
        </el-table-column>
        <el-table-column align="center" label="EGR工时" width="120">
          <template slot-scope="scope">{{ scope.row.fegrgs }}</template>
        </el-table-column>
        <el-table-column align="center" label="创建人" width="120">
          <template slot-scope="scope">{{ scope.row.fcreatemanager }}</template>
        </el-table-column>
        <el-table-column align="center" label="流水号" width="120">
          <template slot-scope="scope">{{ scope.row.fjybjbillno }}</template>
        </el-table-column>
        <el-table-column align="center" label="编号" width="120">
          <template slot-scope="scope">{{ scope.row.fbillno }}</template>
        </el-table-column>
      </el-table>
      <br>
      <!-- <el-pagination
        :total="rowDetail.total"
        :page-sizes="rowDetail.pagesizes"
        :page-size="rowDetail.pagesize"
        :current-page.sync="rowDetail.currentPage"
        class="jy-pagination"
        style="text-align: center; margin-top: 20px;"
        background
        layout="sizes, prev, pager, next, total"
        @size-change="rowDetailSizeChange"
        @current-change="rowDetailCurrentChange"/> -->
    </el-dialog>
  </div>
</template>
<script>
let FRepKey = ''
let opername = ''
const defaultFormThead = []

import HeadTable from '../salary/headTable/index.vue'
import { configColumn, checkStatus } from '../../api/salary'
import { download } from '../../mixins/download.js'
import { common } from '../../mixins/common'
import { pagination } from '../../mixins/pagination'
import { parseTime } from '../../utils/index'
import { tableConfig, apiSql, apiFileSave, downFileUrl, getCBData } from '../../api/account'
import { genAdd, genDel, genList, zlcJXQR } from '../../api/gen'
import '../../styles/common.scss'
import { ScBaoJiaDanZLC, ZLCMX } from '../../api/xmbj'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import XLSXStyle from 'xlsx-style'

export default {
  name: 'Index',
  components: {
    HeadTable
  },
  filters: {
    parseTime(time, type) {
      return parseTime(time, type)
    }
  },
  mixins: [download, common, pagination],
  data() {
    return {
      fid: '',
      fmodelInputModel: false,
      fmodelInput: '',

      value: '',
      options: [],
      FRepKey: '',
      keyword: '',
      fdeleted: '',
      fdeletedList: [

      ],
      fdeletedListDiaL: [

      ],
      gapTime: '',
      start_time: '',
      end_time: '',

      // 表头、表格设置
      tableData: [],
      tableList: [],
      defaultFormThead: [],
      formThead: defaultFormThead,
      dialogThead: [],
      curData: {},

      listLoading: false,
      list: [],
      configModal: false,
      configLoading: false,

      loadingForm: false,
      configList: [],
      key: 0,
      // SQL弹窗
      dialogSQLModal: false,
      loadingFormSQL: false,
      formSQL: {
        gzsql: ''
      },
      rulesSQL: {

      },

      form: {},
      rules: {

      },
      addUserModal: false,
      // loadingForm: false

      fileList: [],

      // 批量删除
      checkData: [],
      selectedData: [],

      // 用户菜单
      menusList: [],
      limits: [],
      userKey: '',
      fmofanName: '',

      fisqrjx: 0,
      fqrlist: [
        {
          finterid: 0,
          fname: '机型未确认'
        },
        // {
        //   finterid: 1,
        //   fname: '确认中'
        // },
        {
          finterid: 2,
          fname: '机型已确认'
        },
        {
          finterid: 5,
          fname: '已完成'
        }
      ],
      brand: '',
      fbrandList: [
        { label: 'WINGD', value: 'WINGD' },
        { label: 'MAN', value: 'MAN' }
      ],
      upData: {},
      fdeptname: '', // 部门
      bmList: [], // 部门
      xlList: [], // 学历
      zwList: [], // 职务
      xbList: [], // 性别
      lzztList: [],
      fileListBasic: [],
      baseList: [],
      upDataBasic: {},

      // 明细
      detailSettings: {
        fmodel: '',
        fbrand: '',
        fbrandList: [
          { label: 'WINGD', value: 'WINGD' },
          { label: 'MAN', value: 'MAN' }
        ],
        fdanweibumen: '0',
        fdanweibumenList: [
          { label: '采购部', value: '1' },
          { label: '技术中心', value: '2' },
          { label: '其他部门', value: '3' },
          { label: '全部', value: '0' }
        ],
        keyword: '',
        fdetailModal: false,
        fdetailKeyword: '',
        fdetailLoading: false,
        detailFormThead: [],
        fdetailData: [],
        // 页脚
        total: 0,
        pagesize: 10,
        pagesizes: [10, 20, 50, 100],
        currentPage: 1
      },

      // 双击明细
      rowDetail: {
        fModal: false,
        fLoading: false,
        tableData: [],
        // 页脚
        total: 0,
        pagesize: 10,
        pagesizes: [10, 20, 50, 100],
        currentPage: 1
      },

      detail: '',
      opername: '',
      detailVisible: false,
      editText: false,
      tableSetExcel: false,
      lookSetShow: false,

      dialogDetailModal: false,
      loadingDetail: false,
      detailRes: {},
      xj: {
        CCS: 0,
        ABS: 0,
        LR: 0,
        DNV: 0,
        BV: 0
      },
      sf: {
        CCS: 0,
        ABS: 0,
        LR: 0,
        DNV: 0,
        BV: 0
      },
      bdcb: {
        CCS: 0,
        ABS: 0,
        LR: 0,
        DNV: 0,
        BV: 0
      },
      // 管理费用
      glfy: {
        CCS: 0,
        ABS: 0,
        LR: 0,
        DNV: 0,
        BV: 0
      },
      // 总成本费用
      zcbfy: {
        CCS: 0,
        ABS: 0,
        LR: 0,
        DNV: 0,
        BV: 0
      }

    }
  },
  async mounted() {
    this.userKey = this.$route.meta.FRepKey
    FRepKey = this.$route.meta.FRepKey
    this.upDataBasic.db = this.globalDb.db
    opername = decodeURIComponent(this.globalDb.fname)
    this.opername = decodeURIComponent(this.globalDb.fname)

    this.upDataBasic.FRepKey = this.$route.meta.FRepKey
    this.lookSetShow = JSON.parse(localStorage.getItem('flookSet'))

    this.upData.db = this.globalDb.db
    this.fmofanName = this.$route.meta.title

    await this.getAllData()

    // 菜单列表（权限）
    const menuRes = JSON.parse(localStorage.getItem('setMenuData'))
    this.menusList = menuRes
    if (menuRes.length >= 1) {
      menuRes.map(it => {
        it.children.map(item => {
          if (item.fobjectid === this.userKey) {
            this.$set(this, 'limits', item.child)
          }
        })
      })
    }
  },
  methods: {
    async rowDetailSizeChange(val) {
      this.rowDetail.currentPage = 1
      this.rowDetail.pagesize = val
      await this.getZLCMX()
    },
    async rowDetailCurrentChange(val) {
      this.rowDetail.currentPage = val
      await this.getZLCMX()
    },
    async detailDbclick(row) {
      // console.log(row, ' row')
      if (row.fjishuremark) {
        this.rowDetail.fModal = true
        await this.getZLCMX(row.fbillno)
      } else {
        this.$message({
          message: '技术未确认,请确认查看明细',
          type: 'error'
        })
      }
    },
    async getZLCMX(fjybjbillno) {
      try {
        this.rowDetail.fLoading = true
        const res = await ZLCMX({
          FRepKey: 14007,
          opername,
          fjybjbillno
        })
        // console.log(res, ' res getZLCMX')
        if (res.Error === 0) {
          // console.log(res, ' res.Data')
          this.rowDetail.tableData = res.Data
          this.rowDetail.fLoading = false
          // console.log(this.rowDetail.tableData, ' this.rowDetail.tableData')
        } else {
          this.$message({
            message: res.Message,
            type: 'error'
          })
          this.rowDetail.fLoading = false
        }
      } catch (error) {
        this.rowDetail.fLoading = false
        console.log(error)
      }
    },
    async detailSizeChange(val) {
      this.detailSettings.currentPage = 1
      this.detailSettings.pagesize = val
      await this.getCBDataList()
    },
    async detailCurrentChange(val) {
      this.detailSettings.currentPage = val
      await this.getCBDataList()
    },
    async searchFmodel() {
      await this.getCBDataList()
    },
    async getCBDataList() {
      try {
        this.detailSettings.fdetailLoading = true
        const res = await getCBData({
          db: this.globalDb.db,
          opername,
          fmodel: this.detailSettings.fmodel,
          fbrand: this.detailSettings.fbrand,
          keyword: this.detailSettings.keyword,
          fdanweibumen: this.detailSettings.fdanweibumen,
          // FRepKey: 26009
          all: 1
          // $fmodel =   $request ->fmodel;
          // $fbrand = $request ->fbrand??'WINGD';
          // $keyword =   $request ->keyword;
          // $fdanweibumen = $request ->fdanweibumen;
          // $FRepKey = $request ->FRepKey;
        })
        if (res.Error === 0) {
          if (res.Data.length) {
            this.detailSettings.detailFormThead = Object.keys(res.Data[0])
          } else {
            this.detailSettings.detailFormThead = []
          }
          setTimeout(() => {
            this.detailSettings.fdetailData = res.Data
          }, 0)
          // console.log(this.formThead, ' this.formThead')
        }
        // this.key = FRepKey
        this.detailSettings.fdetailLoading = false
      } catch (error) {
        this.detailSettings.fdetailLoading = false
      }
    },
    async editData(row, column, cell, event) {
      console.log(column.id, column.property, column, row, event, 'column')
      if (column.property === 'ftaxsinglezjcl') {
        this.detailSettings.fmodel = row.fmodel
        this.detailSettings.fbrand = row.fbrand
        this.detailSettings.fdetailModal = true
        await this.getCBDataList()
      }
    },
    onPlus() {
      this.$router.push('/jybj/zlcjsLoad')
    },
    exportSCBJD() {
      var xlsxParam = {
        raw: true
      }
      const workbook = XLSX.utils.book_new()

      const ws1 = XLSX.utils.table_to_sheet(document.querySelector('#bjd_qdx'), xlsxParam)
      const ws2 = XLSX.utils.table_to_sheet(document.querySelector('#bjd_bdx'), xlsxParam)
      const ws3 = XLSX.utils.table_to_sheet(document.querySelector('#bjd_zjfy'), xlsxParam)

      let a = XLSX.utils.sheet_to_json(ws1, { header: 1 })
      const b = XLSX.utils.sheet_to_json(ws2, { header: 1 })
      const c = XLSX.utils.sheet_to_json(ws3, { header: 1 })

      a = a.concat(['']).concat(b).concat(['']).concat(c)
      const worksheet = XLSX.utils.json_to_sheet(a, { skipHeader: true })
      XLSX.utils.book_append_sheet(workbook, worksheet, '报价格式')
      const wbData = workbook['Sheets']['报价格式']
      this.setExlStyle(wbData)
      const wbout = XLSXStyle.write(workbook, {
        type: 'buffer'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: 'application/octet-stream;charset=utf-8"'
          }), '报价格式.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    setExlStyle(data) {
      const borderAll = { // 单元格外侧框线
        top: {
          style: 'thin'
        },
        bottom: {
          style: 'thin'
        },
        left: {
          style: 'thin'
        },
        right: {
          style: 'thin'
        }
      }

      data['!cols'] = []
      for (const key in data) {
        if (data[key] instanceof Object) {
          data[key].s = {
            border: borderAll,
            alignment: {
              horizontal: 'center', // 水平居中对齐
              vertical: 'center'
            },
            font: {
              sz: 11
            },
            bold: true,
            numFmt: 0
          }

          data['!cols'].push({ wch: 20 })
        }
      }
      return data
    },
    async getScBaoJiaDanZLC(fid) {
      try {
        const res = await ScBaoJiaDanZLC({
          opername: decodeURIComponent(this.globalDb.fname),
          fid
        })
        console.log(res, ' res ScBaoJiaDanZLC')
        if (res.Error === 0) {
          this.detailRes = res.Data

          const xjOtherAll = Number(this.detailRes.ftaxSinglezjcl) + // 直接材料
                        Number(this.detailRes.fjiazhangcb) + // 加账成本
                        Number(this.detailRes.fPatentfee) + // 专利费
                        // Number(this.detailRes.fshipfeeCCS) + // 船检费等费用CSS ------
                        Number(this.detailRes.femissionfee) + // 排放测试费
                        Number(this.detailRes.fyouqifee) + // 油气费
                        Number(this.detailRes.fNooneyouqifee) + // 油气费-非首台
                        Number(this.detailRes.ffucaitotal) + // 辅材、低耗、劳保等
                        Number(this.detailRes.fsdTotal) + // 水电费
                        // Number(this.detailRes.fDrawingCCS) + // 图纸送审费CCS ------
                        Number(this.detailRes.fyunfei) + // 运保费
                        Number(this.detailRes.fsaleCost) + // 售后调试及维护成本
                        Number(this.detailRes.fqualityCost) + // 质量成本
                        Number(this.detailRes.fweiwaifee) + // 委外费用
                        Number(this.detailRes.fDrawingfee) + // 图纸费
                        Number(this.detailRes.fworkwhole) + // 特定工装
                        Number(this.detailRes.fcutter) + // 特定刀具
                        Number(this.detailRes.fzhijieRg) + // 直接人工
                        Number(this.detailRes.fzstiaojian) + // 赠送备件
                        Number(this.detailRes.fyongjin) // 佣金
          // 小计
          this.xj.CCS = Number(this.detailRes.fshipfeeCCS) + Number(this.detailRes.fDrawingCCS) + xjOtherAll
          this.xj.ABS = Number(this.detailRes.fshipfeeABS) + Number(this.detailRes.fDrawingABS) + xjOtherAll
          this.xj.LR = Number(this.detailRes.fshipfeeLR) + Number(this.detailRes.fDrawingLR) + xjOtherAll
          this.xj.DNV = Number(this.detailRes.fshipfeeDNVGL) + Number(this.detailRes.fDrawingDNVGL) + xjOtherAll
          this.xj.BV = Number(this.detailRes.fshipfeeBV) + Number(this.detailRes.fDrawingBV) + xjOtherAll
          // 税费及财务费用
          this.sf.CCS = Number(this.xj.CCS * 1000000 * 0.05) / 1000000
          this.sf.ABS = Number(this.xj.ABS * 1000000 * 0.05) / 1000000
          this.sf.LR = Number(this.xj.LR * 1000000 * 0.05) / 1000000
          this.sf.DNV = Number(this.xj.DNV * 1000000 * 0.05) / 1000000
          this.sf.BV = Number(this.xj.BV * 1000000 * 0.05) / 1000000
          // 变动成本小计
          this.bdcb.CCS = this.xj.CCS + this.sf.CCS
          this.bdcb.ABS = this.xj.ABS + this.sf.ABS
          this.bdcb.LR = this.xj.LR + this.sf.LR
          this.bdcb.DNV = this.xj.DNV + this.sf.DNV
          this.bdcb.BV = this.xj.BV + this.sf.BV
          // 管理费用
          this.glfy.CCS = this.bdcb.CCS + Number(this.detailRes.fzhejiu)
          this.glfy.ABS = this.bdcb.ABS + Number(this.detailRes.fzhejiu)
          this.glfy.LR = this.bdcb.LR + Number(this.detailRes.fzhejiu)
          this.glfy.DNV = this.bdcb.DNV + Number(this.detailRes.fzhejiu)
          this.glfy.BV = this.bdcb.BV + Number(this.detailRes.fzhejiu)
          // ④总成本费用
          this.zcbfy.CCS = this.bdcb.CCS + Number(this.detailRes.fzhejiu) + this.glfy.CCS
          this.zcbfy.ABS = this.bdcb.ABS + Number(this.detailRes.fzhejiu) + this.glfy.ABS
          this.zcbfy.LR = this.bdcb.LR + Number(this.detailRes.fzhejiu) + this.glfy.LR
          this.zcbfy.DNV = this.bdcb.DNV + Number(this.detailRes.fzhejiu) + this.glfy.DNV
          this.zcbfy.BV = this.bdcb.BV + Number(this.detailRes.fzhejiu) + this.glfy.BV
        }
      } catch (error) {
        console.log(error)
      }
    },

    // 刷新
    refresh() {
      window.location.reload()
    },

    async toDetail(data) {
      this.detailVisible = true
      this.detail = data
    },

    selectFBirthday(val) {
      this.form.fbirthday = parseTime(val, '{y}-{m}-{d}')
    },
    selectFHireDate(val) {
      this.form.fhiredate = parseTime(val, '{y}-{m}-{d}')
    },
    selectFLeaveDate(val) {
      this.form.fleavedate = parseTime(val, '{y}-{m}-{d}')
    },
    // -----------------上传开始---------------------
    beforeAvatarUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xls' || testmsg === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!extension) {
        this.$message({
          message: '上传文件只能是 xls/xlsx格式!',
          type: 'warning'
        })
      }
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 1MB!',
          type: 'warning'
        })
      }

      const fd = new FormData()
      fd.append('file', file)

      if (extension) {
        return true
      } else {
        this.$message.warning('只能上传excel文件格式xls/xlsx')
        return false
      }
    },

    async submitUpload() {
      this.$refs.upload.submit()
    },

    handleRemove(file, fileList) {

    },
    handlePreview(file) {

    },
    exceed() {
      // 重复选择文件,弹出错误弹窗
      this.$message('最多仅支持上传一个文件')
    },
    notice(e) {
      if (e.code === 200) {
        this.$message(e.message)
      } else {
        this.$message(e.message)
      }
    },
    // -----------------上传结束---------------------
    // 表头数据
    async getAllHeadData() {
      try {
        this.listLoading = true
        this.header = []
        this.headerKeys = []
        this.listData = []
        const res = await configColumn({
          db: this.globalDb.db,
          opername,
          FRepKey
        })
        this.listLoading = false
        this.formThead = res.Data
        // this.tableList = []
        this.formThead.map(item => {
          this.tableList.map(it => {
            if (item.freptype === 131) {
              it[item.frepfld] = Number(it[item.frepfld]).toFixed(item.fdecplaces)
            }
          })
        })
        // this.tableData = this.tableList.slice()
        let tableTemp
        if (this.selectedData.length) {
          tableTemp = this.selectedData
        } else {
          tableTemp = this.tableList.slice()
        }

        // fyunfei 运保费
        // fsalecost 售后成本
        // fzhejiu 折旧

        // 获取显示表头键值对
        this.formThead.filter(item => {
          if (!item.frephide) {
            this.header.push(item.frepcap)
            this.headerKeys.push(item.frepfld)
          }
        })
        // 获取显示表体数据
        // const listData = this.tableList.slice()
        const listData = tableTemp.slice()
        listData.map((item, index) => {
          this.listData[index] = {}
          this.headerKeys.map(it => {
            this.listData[index][it] = item[it]
          })
        })

        // 去除内码
        const arr = res.Data.slice()
        arr.map((item, index) => {
          if (item.frepfld === 'fid') {
            arr.splice(index, 1)
          }
        })

        this.dialogThead = arr.filter(item => item.funcontrol !== 1)
      } catch (error) {
        this.listLoading = false
      }
    },

    // 表体数据————erp职员列表
    async getAllBodyData() {
      try {
        this.listLoading = true
        const res = await genList({
          db: this.globalDb.db,
          opername,
          keyword: this.keyword,
          brand: this.brand,
          fisqr: this.fisqrjx,

          limit: this.total,
          page: this.currentPage,
          FRepKey
        })
        this.listLoading = false

        this.tableList = res.Data
        this.total = res.total
      } catch (error) {
        this.listLoading = false
      }
    },
    // 导出数据
    async downData() {
      await this.getAllBodyData()
      await this.getAllHeadData()
      await this.exportData()
    },
    async finputConfirm() {
      this.tableData.map(it => {
        if (Number(it.fid) === Number(this.fid)) {
          this.$set(it, 'fmodel', this.fmodelInput)
        }
      })
      this.fmodelInputModel = false
    },
    async confirmJx(val) {
      if (!this.checkData.length) {
        this.$message({
          message: '请选择表格行数据',
          type: 'error'
        })
        return
      }
      const data = this.selectedData[0]
      this.fid = data.fid

      this.$confirm('走流程机型，请确认？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '放弃确认'
      })
        .then(async() => {
          const res = await zlcJXQR({ FRepKey, fisqr: val, data: this.selectedData, opername: decodeURIComponent(this.globalDb.fname), fid: this.checkData.join(',') })
          if (res.Error === 0) {
            this.$message({
              type: 'success',
              message: '确认成功'
            })
            await this.getAllData()
          } else {
            this.$message({
              type: 'error',
              message: res.Message
            })
          }
        })
        .catch(action => {
          this.$message({
            type: 'info',
            message: action === 'cancel'
              ? '放弃确认'
              : '停留在当前页面'
          })
        })
    },
    async getAllData() {
      await this.getBodyData()
      await this.getHeadData()
    },

    selectSettings(val) {
      if (val === 0) {
        this.settings()
      } else if (val === 1) {
        this.dialogSQL()
      }
    },
    settings() {
      this.configModal = true
      this.getTableConfig()
    },

    // 更新数据
    async getUpdateConfigData() {
      await this.getTableConfig()
      await this.getBodyData()
      await this.getHeadData()
    },

    // SQL修改/更新
    async dialogSQL() {
      this.dialogSQLModal = true
      try {
        const res = await apiSql({
          db: this.globalDb.db,
          opername,
          FRepKey
        })

        if (res.Error === 0) {
          this.formSQL.gzsql = res.Data
          this.formSQL.FRepKey = FRepKey
        }
        setTimeout(() => {
          this.$refs['formSQL'].clearValidate()
        })
      } catch (error) {
        // console.log(error)
      }
    },

    confirmSQL() {
      this.$refs['formSQL'].validate(async(valid) => {
        if (valid) {
          try {
            this.formSQL.db = this.globalDb.db
            this.formSQL.opername = opername
            const res = await apiFileSave(this.formSQL)
            if (res.Error === 0) {
              this.dialogSQLModal = false
              this.$message({
                message: res.Message,
                type: 'success'
              })
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            // console.log(error)
          }
        } else {
          return false
        }
      })
    },

    async getTableConfig() {
      try {
        this.configLoading = true
        const res = await tableConfig({
          db: this.globalDb.db,
          opername,
          key: FRepKey
        })
        this.configList = res.Data
        this.key = FRepKey
        this.configLoading = false
      } catch (error) {
        this.configLoading = false
      }
    },

    // 表头数据
    async getHeadData() {
      try {
        this.listLoading = true
        this.header = []
        this.headerKeys = []
        this.listData = []
        const res = await configColumn({
          db: this.globalDb.db,
          opername,
          FRepKey
        })
        this.listLoading = false
        this.formThead = res.Data
        // this.tableList = []
        this.formThead.map(item => {
          this.tableList.map(it => {
            if (item.freptype === 131) {
              it[item.frepfld] = Number(it[item.frepfld]).toFixed(item.fdecplaces)
            }
          })
        })
        this.tableData = this.tableList.slice()

        // fyunfei 运保费
        // fsalecost 售后成本
        // fzhejiu 折旧

        // 获取显示表头键值对
        this.formThead.filter(item => {
          if (!item.frephide) {
            this.header.push(item.frepcap)
            this.headerKeys.push(item.frepfld)
          }
        })
        // 获取显示表体数据
        const listData = this.tableList.slice()
        listData.map((item, index) => {
          this.listData[index] = {}
          this.headerKeys.map(it => {
            this.listData[index][it] = item[it]
          })
        })

        // 去除内码
        const arr = res.Data.slice()
        arr.map((item, index) => {
          if (item.frepfld === 'fid') {
            arr.splice(index, 1)
          }
        })

        this.dialogThead = arr.filter(item => item.funcontrol !== 1)
      } catch (error) {
        this.listLoading = false
      }
    },

    // 表体数据————erp职员列表
    async getBodyData() {
      try {
        this.listLoading = true
        const res = await genList({
          db: this.globalDb.db,
          opername,
          keyword: this.keyword,
          brand: this.brand,
          fisqr: this.fisqrjx,

          limit: this.pagesize,
          page: this.currentPage,
          FRepKey
        })
        this.listLoading = false

        this.tableList = res.Data
        this.total = res.total
      } catch (error) {
        this.listLoading = false
      }
    },
    async selectBrand() {
      await this.searchUser()
    },
    async searchUser() {
      await this.getAllData()
    },
    async handleSizeChange(val) {
      this.currentPage = 1
      this.pagesize = val
      await this.getAllData()
    },
    async handleCurrentChange(val) {
      this.currentPage = val
      await this.getAllData()
    },
    salaryCurrentChange(val) {
      this.curData = val
    },

    // 下载
    async handleDownload() {
      const res = await downFileUrl({
        db: this.globalDb.db,
        opername,
        FRepKey
      })
      if (res.Error === 0) {
        this.tableSetExcel = true
        this.url = res.Data
      } else {
        this.$message({
          message: res.Message,
          type: 'error'
        })
      }
    },

    downloadFile1() {
      this.tableSetExcel = false
      window.open('/api/downloadFile?FRepKey=' + FRepKey)
    },

    // -----------------上传模板开始---------------------
    beforeAvatarUploadBasic(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xls' || testmsg === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!extension) {
        this.$message({
          message: '上传文件只能是 xls/xlsx格式!',
          type: 'warning'
        })
      }
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 1MB!',
          type: 'warning'
        })
      }

      const fd = new FormData()
      fd.append('file', file)

      if (extension) {
        return true
      } else {
        this.$message.warning('只能上传excel文件格式xls/xlsx')
        return false
      }
    },

    async submitUploadBasic() {
      this.$refs.uploadBasic.submit()
    },

    handleRemoveBasic(file, fileList) {

    },
    handlePreviewBasic(file) {

    },
    exceedBasic() {
      // 重复选择文件,弹出错误弹窗
      this.$message('最多仅支持上传一个文件')
    },

    noticeBasic(e) {
      if (e.Error === 0) {
        this.$message(e.Message)
        this.getAllData()
        this.$refs.uploadBasic.clearFiles()
      } else {
        this.$message(e.Message)
      }
    },

    // 添加
    async addUser() {
      this.editText = false
      this.form = {}
      const data = {}
      this.dialogThead.map(item => { data[item.frepfld] = '' })
      for (const i in data) {
        this.$set(this.form, i, data[i])
      }
      setTimeout(() => {
        this.$refs['form'].clearValidate()
      })

      this.addUserModal = true
    },

    // 修改
    async editUser() {
      const data = this.selectedData[0]
      if (data && Number(data.fstatuscb) === 1) {
        this.$message({
          message: '已审核，不能修改！',
          type: 'error'
        })
        return
      }

      this.editText = true
      this.form = {}
      if (this.selectedData.length !== 1) {
        this.$message({
          message: '请选中要编辑的一行',
          type: 'warning'
        })
        return
      }

      this.dialogThead.map(item => { this.$set(this.form, item.frepfld, '') })
      this.form.fid = 0
      this.addUserModal = true
      for (const i in this.form) {
        this.form[i] = data[i]
        this.dialogThead.map(item => {
          if (item.frepmeg === 1 && i === item.frepfld && !data[i]) {
            this.form[i] = ''
          }
        })
      }

      setTimeout(() => {
        this.$refs['form'].clearValidate()
      })
    },

    async confirm() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          this.loadingForm = true
          try {
            this.form.db = this.globalDb.db
            this.form.opername = opername
            this.form.FRepKey = FRepKey

            const res = await genAdd(this.form)
            if (res.Error === 0) {
              this.loadingForm = false
              this.addUserModal = false
              this.$message({
                message: res.Message,
                type: 'success'
              })

              await this.getAllData()
            } else {
              this.loadingForm = false

              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            this.loadingForm = false
          }
        } else {
          return false
        }
      })
    },

    async delUser() {
      const data = this.checkData
      if (data.length < 1) {
        this.$message({
          message: '请选中要删除的一行',
          type: 'warning'
        })
        return
      }

      const dataTemp = this.selectedData
      const isFstatus = dataTemp.filter(it => Number(it.fstatuscb) === 1)

      if (isFstatus.length) {
        this.$message({
          message: '已审核，不能删除！',
          type: 'error'
        })
        return
      }

      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning'
      }).then(async() => {
        const fid = data.join(',')
        const res = await genDel({
          db: this.globalDb.db,
          opername,
          data: this.selectedData,
          fid: fid,
          FRepKey

        })
        if (res.Error === 0) {
          this.$message({
            message: res.Message,
            type: 'success'
          })
          await this.getAllData()
          return
        }
        this.$message({
          message: res.Message,
          type: 'error'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 1—审核，0—反审
    async check(Fstatus) {
      if (!this.checkData.length) {
        this.$message({
          message: '请选择表格行数据',
          type: 'error'
        })
        return
      }
      if (Number(Fstatus) === 1) {
        this.$confirm('是否审核, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning'
        }).then(async() => {
          try {
            const res = await checkStatus({
              db: this.globalDb.db,
              opername: decodeURIComponent(this.globalDb.fname),
              loginname: decodeURIComponent(this.globalDb.fname),
              FRepKey,
              Fstatus, // 1—审核，0—反审
              fid: this.checkData.join(',')

            })
            if (res.Error === 0) {
              this.$message({
                message: res.Message,
                type: 'success'
              })
              await this.getAllData()
            } else {
              this.loadingForm = false
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            console.log(error)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        try {
          const res = await checkStatus({
            db: this.globalDb.db,
            opername: decodeURIComponent(this.globalDb.fname),
            loginname: decodeURIComponent(this.globalDb.fname),
            FRepKey,
            Fstatus, // 1—审核，0—反审
            fid: this.checkData.join(','),
            appname: ''
          })
          if (res.Error === 0) {
            this.$message({
              message: res.Message,
              type: 'success'
            })
            await this.getAllData()
          } else {
            this.loadingForm = false
            this.$message({
              message: res.Message,
              type: 'error'
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
    },
    handleSelectionChange(val) {
      // console.log(val, ' val')
      this.checkData = []
      this.selectedData = val
      val.map(it => {
        this.checkData.push(it.fid)
      })
    }

  }
}

</script>
<style lang="scss" scoped>
.config-dialog ::v-deep .el-dialog {
  width: 100%;
  .el-dialog_body {
    padding: 0px 20px;
  }
}
  .detail {
    // margin: 100px auto;
    // width: 1024px;
    position: relative;
    width: 100%;
    margin-bottom: 30px;
    // border: 1px solid red;
    margin-top: -30px;
    .btn_box {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      top: -40px;
      overflow: hidden;
      margin-bottom: 2px;
    }
  }
  /* 滚动条宽度 */
  ::-webkit-scrollbar {
    width: 0px;
    background-color: transparent;
  }

  /* 滚动条颜色 */
  ::-webkit-scrollbar-thumb {
    background-color: #27314d;
  }

  table {
    width: 100%;
    border-spacing: 0px;
    border-collapse: collapse;
  }

  table caption {
    font-weight: bold;
    font-size: 16px;
    line-height: 16px;
    text-align: left;
    margin-top: 10px;
  }

  table th, table td {
    height: 20px;
    text-align: center;
    border: 1px solid gray;
  }

  table thead .title {
    color: white;
    background-color: #38F;
  }

  table tbody {
    display: block;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  table tfoot {
    background-color: #71ea71;
  }

  table thead tr, table tbody tr, table tfoot tr {
    box-sizing: border-box;
    table-layout: fixed;
    display: table;
    width: 100%;
  }

  table tbody tr:nth-of-type(odd) {
    background: #EEE;
  }

  table tbody tr:nth-of-type(even) {
    background: #FFF;
  }

  table tbody tr td {
    border-bottom: none;
  }
  table {
    border-bottom: 1px solid gray;
  }
  ::v-deep .finput-dialog.el-dialog__wrapper  .el-dialog__body {
    height: 150px;
  }
  .config-dialog ::v-deep .el-dialog__body {
    padding: 0 20px;
    height: 600px;
  }
.detail-dialog {
  widows: 80%;
}

.row-detail-dialog ::v-deep .el-dialog {
  width: 80%;
  .el-dialog_body {
    padding: 0px 20px;
  }
}
</style>

